package com.bw.controller;

import com.alibaba.fastjson.JSON;
import com.bw.entity.User;
import com.bw.mapper.UserMapper;
import org.spring.kun.common.Md5Utils;
import org.spring.kun.common.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.concurrent.TimeUnit;

@Controller
public class LoginController {
    @Autowired
    UserMapper userMapper;

    @Autowired
    RedisTemplate redisTemplate;

    @RequestMapping("/loginPage.do")
    public String loginPage(){

        return "login";
    }

    @RequestMapping("/login.do")
    public String login(@Valid User loginUser, BindingResult result, Model model, HttpServletRequest request, HttpServletResponse response){

        if (result.hasErrors()){

            model.addAttribute("error",result.getAllErrors().get(0).getDefaultMessage());
            return "login";

        }

       User userDB =  userMapper.selectByPhone(loginUser.getPhone());
        if (userDB == null){
            model.addAttribute("error","手机号不存在");
            return "login";
        }
        String password = userDB.getPassword();
        String salt = userDB.getSalt();

        String loginUserPassword = loginUser.getPassword();

        String md5String = Md5Utils.getMD5String(loginUserPassword + salt);

        if (!md5String.equals(password)){
            model.addAttribute("error","密码错误");
            return "login";

        }
        // 给这个用户颁发令牌 存到他的浏览器里,加密数据库里的用户  30分钟过期
        userDB.setPassword("");
        TokenUtils.responseTokenByCookie(userDB,response,30);

        // 把用户信息存入Redis
        redisTemplate.opsForValue().set(userDB.getPhone(), JSON.toJSONString(userDB),30, TimeUnit.MINUTES);
        return "redirect:list.do";
    }



    @RequestMapping("/list.do")
    public String list(HttpServletRequest request,Model model){
        // 获取当前登录用户( 已经有昵称和头像了， 因为用户绑定账号之后会重新加密得到令牌)
        User userFromRequest = TokenUtils.getLoginUserFromRequest(request, User.class);

        model.addAttribute("nickName",userFromRequest.getNickName());
        model.addAttribute("avatarUrl",userFromRequest.getAvatarUrl());

        return "list";
    }

}
